#!/usr/local/bin/python2.5
import utility
from socket import *
import array
import binascii
import struct
import time
import sys
import os
import time
import random

def send_data(sock, data):
    length = len(data)
    send_len = 0
    try:
        while send_len < length:
            send_len += sock.send(data[send_len:])
    except timeout:
        return
    except Exception, ex:
        print 'error',ex
        return
    return send_len

def recv_data(sock, length):
    try:
        data_package = ""
        left_length = length
        while 1:
            data = sock.recv(left_length)
            if not data:
                globalDef.logger.warn('client close connection!')
                return data
            data_package += data
            left_length -= data.__len__()
            if left_length<=0:
                return data_package
    except timeout:
        print 'receive timeout'
        return
    except Exception, ex:
        print 'error', ex
        return 

def send_mail_test():
        sendmailpath = '/usr/local/bin/sendEmail -s mail.sandai.net  -f monitor@xunlei.com  -t  qianyaofeng@xunlei.com -cc qianyaofeng@xunlei.com -cc qianyaofeng@xunlei.com -xu monitor@xunlei.com  -xp 121212 -u "pingServer" -m "tel monitor from t0334" '
        os.system(sendmailpath)

def send_mail():
        sendemailpath ='/usr/local/bin/sendEmail -s mail.sandai.net  -f monitor@xunlei.com  -t qianyaofeng@xunlei.com -cc yangshengqian@xunlei.com -cc alarm@xunlei.com -cc caozhenfei@xunlei.com -cc hepengfei@xunlei.com -xu monitor@xunlei.com -xp 121212 -u "rising hezuo query xbase fail c0349" -m "rising hezuo query xbase fail c0349" '
        os.system(sendemailpath)

def encodeBody(cid):

    offset = 0
    arr = array.array('B', '\x00'*4096)

    arr_offset_list = [arr, offset]

    # version
    utility.net_oreder_putInt(arr_offset_list, 100)
    # sign
    utility.net_oreder_putInt(arr_offset_list, 99887766)
    #
    utility.net_oreder_putInt(arr_offset_list, 0)
    #
    utility.net_oreder_putInt(arr_offset_list, 1)

    # bodylen
    utility.net_oreder_putInt(arr_offset_list, 40)

    utility.net_oreder_putInt(arr_offset_list, 0)
    utility.net_oreder_putInt(arr_offset_list, 0)
    utility.net_oreder_putInt(arr_offset_list, 0)
    utility.net_oreder_putInt(arr_offset_list, 0)

    # command id
    utility.net_oreder_putInt(arr_offset_list, 101)

    gcid = cid
    #cid
    utility.net_oreder_putLongString(arr_offset_list,cid)
   
    utility.net_oreder_putInt(arr_offset_list, 0)
    # count
    utility.net_oreder_putInt(arr_offset_list, 5000)

    bodylen = arr_offset_list[1]
    #bodylen = htonl(bodylen)

    struct.pack_into('!I', arr, 16, bodylen)

    return arr[:arr_offset_list[1]].tostring()

def parseReturnData(head):
    try:
        offset = 0
        arrayhead = array.array('B', head)
        arr_offset_list = [arrayhead, offset]

        pro_ver = utility.getInt(arr_offset_list)
        sequence =utility.getInt(arr_offset_list)
        sequence =utility.getInt(arr_offset_list)
        sequence =utility.getInt(arr_offset_list)
        
        bodylen = utility.netOrder_getInt(arr_offset_list)
        bodylen = bodylen - 40
        return bodylen
    except Exception, ex:
        print 'error', ex
        return

def parseBodyData(body):
    offset = 0
    arrayhead = array.array('B', body)
    ar = [arrayhead, offset]
    result = utility.netOrder_getInt(ar)
    count = utility.netOrder_getInt(ar)
    print "query success, res num: %u" % count

    for i in range(count):
        cid = utility.netOrder_getString(ar)
        gcid = utility.netOrder_getString(ar)
        filesize = utility.netOrder_get64(ar)
        peerid = utility.netOrder_getString(ar)
        
        #print 'res %u' % i
        #print '\tcid: %s' % binascii.b2a_hex(cid)
        #print '\tfilesize: %u' % filesize
        #print '\tgcid: %s' % binascii.b2a_hex(gcid)
        #print '\tpeerid: %s' % peerid

def random_cid():
    arr = array.array('B', '\x00'*20)

    for i in range(20):
        b = random.randint(0,0xFF)
        arr[i] = b

    return arr.tostring()

def start():
    ip = "58.61.39.244"
    port = 9596
    iptuple = (ip, port)
    sock = socket(AF_INET, SOCK_STREAM)
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sock.settimeout(120)
    try:
        sock.connect(iptuple)
    except Exception, ex:
        print 'error',ex
        return

    #while True:
    for line in sys.stdin:
        #cid = random_cid()
        cid_str = line.strip() 
        cid = binascii.a2b_hex(cid_str)

        #print 'query cid: %s' % binascii.b2a_hex(cid)
        print 'query cid: %s' % cid_str
        noEncryptBody = encodeBody(cid)

        try:
            send_len = send_data(sock, noEncryptBody)
        except Exception, ex:
            print ex

        if not send_len:
            print ex

        head = recv_data(sock, 40)

        if head:
            bodylen = parseReturnData(head)

            body = recv_data(sock, bodylen)

            if body:
                print 'recv body len = ', len(body)

                parseBodyData(body)
                if not body:
                    print 'parse return data failed'


if __name__ == '__main__':
    start()
